#! /usr/bin/env python
# coding: utf-8

"""这个脚本实际上是在源码根目录下，递归查找以.git结尾的目录，然后做commit-msg
的软链接，commit-msg是产生Changed-Id的一个hook脚本
"""

import os
import itertools

def all_equal(elements):
    first_element = elements[0]

    for other_element in elements[1:]:
        if other_element != first_element:
            return False

    return True

def common_prefix(*sequences):
    if not sequences:
        return [], []

    common = []

    for elements in itertools.izip(*sequences):
        if not all_equal(elements):
            break
        common.append(elements[0])

    return common, [sequence[len(common):] for sequence in sequences]

def relpath(p1, p2, sep=os.path.sep, pardir=os.path.pardir):
    common, (u1, u2) = common_prefix(p1.split(sep), p2.split(sep))

    if not common:
        return p2

    return sep.join([pardir]*len(u1) + u2)

def create_link():
    abspath = os.path.abspath('.')

    if not os.path.exists('.repo'):
        print "No .repo dir found! Please put it into root of android source!"
        sys.exit(-1)

    for dir in os.listdir('.'):
        if dir != '.repo':
            for dirpath, dirnames, filenames in os.walk(dir, topdown=True):
                if dirnames.count('.git') == 1:
                     src = os.path.join(abspath, '.repo/repo/hooks/commit-msg')
                     dst = os.path.join(abspath, dirpath, '.git/hooks/')

                     if os.listdir(dst).count("commit-msg") == 0:
                         os.symlink(relpath(dst, src), dst + '/commit-msg')
                         print 'create_link done: {0}'.format(dst)
    print 'All is done !'

def usage():
    print 'Usage: python create_hook_link.py'
    sys.exit(-1)

if __name__ == '__main__':
    import sys
    if len(sys.argv) > 1:
        usage()
    create_link()
